/* Copyright 2007 Gearbox Software - http://www.gearboxsoft.com
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 
     http:www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.*/
namespace GearBlog.Web.Validators
{
	using System.Collections;
	using Castle.Components.Validator;
	using GearBlog.Web.Models;

	public class ValidateRoleListAttribute:AbstractValidationAttribute
	{
		public ValidateRoleListAttribute()
		{
		}

		public ValidateRoleListAttribute(string errorMessage) : base(errorMessage)
		{

		}

		public override IValidator Build()
		{
			RoleListValidator validator=new RoleListValidator();
			ConfigureValidatorMessage(validator);
			return validator;
		}
	}
	public class RoleListValidator:AbstractValidator
	{
		public override bool IsValid(object instance, object fieldValue)
		{
			if (fieldValue.ToString().Trim().Length > 0)
			{
				string[] roleNames = ((string) fieldValue).Split(',');
				foreach (string roleName in roleNames)
					if (Role.FindByName(roleName.Trim()) == null)
						return false;
			}

			return true;
		}
		public override void ApplyWebValidation(WebValidationConfiguration config, InputElementType inputType, IWebValidationGenerator generator, IDictionary attributes, string target)
		{
			base.ApplyWebValidation(config, inputType, generator, attributes, target);
		}
		public override bool SupportsWebValidation
		{
			get { return false; }
		}
		protected override string BuildErrorMessage()
		{
			return "Unable to find one or more role name.";
		}
		
	}
}
